<template>
	<view class="content" style="background: none;">
		<!-- three -->
		<!-- <view class="load">正在加载模型，请耐心等待...</view> -->
		<view id="threeView" @touchstart="anms=false" @touchend="anms=true"></view>
		<!-- #ifndef APP-PLUS || H5 -->
		<view>非 APP、H5 环境不支持</view>
		<!-- #endif -->

	</view>
</template>
<script  module="three" lang="renderjs">
	const THREE = require('node_modules/three/build/three.min.js')
	import {
		OrbitControls
	} from 'node_modules/three/examples/jsm/controls/OrbitControls.js'
	import {
		GLTFLoader
	} from 'node_modules/three/examples/jsm/loaders/GLTFLoader.js';
	export default {	
		name: "three",
		props: {
			src: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				container: null, //挂载点
				// stats: null,//性能插件
				clock: null, //时钟对象
				controls: null, //轨道控制器
				camera: null, //摄像机
				scene: null, //场景
				renderer: null, //渲染器
				mixer: null, //加载模型的动画
				axes: null, //三维线
				object:null,
				centroid:null,//三维向量
				// src:'',
				loading: false,
				anms: true,
			}
		},
		created(){
			console.log('预览页',this.src)	
			this.$nextTick(()=>{
				this.init()
				this.animate()
			})
			
			// this.CheckImgExists(this.src).then(()=>{
			// 	    this.loading = true
			// 		this.init()
			// 		this.animate()
					
			// }).catch(()=>{
			// 	this.init()
			// 	this.animate()
				
			// })
		},
		onLoad(options){
			
			console.log('预览页')	
		},
		onReady() {
				console.log('预览页')	
			//判断地址是否有效
			
			
			
			
		},
		methods: {
			//判断图片地址是否404
			CheckImgExists(imgurl) {
			  return new Promise(function(resolve, reject) {
			    var ImgObj = new Image(); //判断图片是否存在
			    ImgObj.src = imgurl;
			    ImgObj.onload = function(res) {
			      resolve(res);
			    }
			    ImgObj.onerror = function(err) {
			      reject(err)
			    }
			  })
			},
			init() {
				
				var _this = this

				this.container = document.getElementById('threeView'); //获取挂载点
				// console.log(new THREE)

				this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 1000); //摄像机

				this.camera.position.set(0, 0, 15); //调整摄像机位置  x  y  z 

				this.scene = new THREE.Scene(); //创建场景
				console.log('scene', this.scene) //打印

				this.clock = new THREE.Clock(); //时钟对象
				console.log('clock', this.clock)
				// this.camera.lookAt(this.scene.position);
				//设置三维线
				// this.axes = new THREE.AxesHelper(5); //设置一个三维坐标轴，参数位轴的长度  默认参数为 1
				// this.axes.setColors(0x00ffff,0xffff00,0xff00ff);//设置 x y z 轴的颜色
				
				// this.centroid = new THREE.Vector3();; //设置一个三维常量
				// console.log('三维向量', this.centroid)
				this.scene.add(this.axes); //添加到场景对象中
				console.log('摄像机', this.camera)
				this.scene.add(this.camera);
				// manager  纹理
				
				function loadModel() {
					const {object,scene} = _this;
					const box = new THREE.Box3();
					// console.log(box.setFromObject)
					box.setFromObject(object);
					box.max.sub(box.min);
					const {x,y,z} = box.max;
					const size = 5; // 设置标准尺寸
					// 实际尺寸过小就放大,实际尺寸过大就缩小
					const maxSide = Math.max(x, y, z); // 取最大的那一条边为基准
					const dist = size / maxSide; // 计算缩放比例
					object.scale.set(dist, dist, dist);
					object.position.setY(-0.5*y*dist+1);
					// object.children[0].material.map = texture
					
					scene.add( object );
				}
				
				const manager = new THREE.LoadingManager( loadModel );
				
				// texture  纹理的来源
				
				const textureLoader = new THREE.TextureLoader( manager );
				const texture = textureLoader.load( _this.DiffuseUrl );//颜色贴图
				const bgc = textureLoader.load('https://imgcdn.ecbao.cn/nft/assets/header_bg.jpg' );//添加背景

				_this.scene.background=bgc
				// console.log( '1111111',_this.DiffuseUrl)
				// const emissive = textureLoader.load( '../../../static/mianju/lambert2SG_Emissive.png' );//自发光贴图
				// const normal = textureLoader.load( '../../../static/mianju/lambert2SG_Normal.png' );//法线贴图
				// const ao = textureLoader.load( '../../../static/mianju/lambert2SG_Mixed_AO.png' );//环境贴图
				// const alpha = textureLoader.load( '../../../static/mianju/lambert2SG_Opacity.png' );//透明贴图
				// const bump = textureLoader.load( '../../../static/mianju/lambert2SG_Height.png' );//高度贴图
				
				// console.log('emissive',emissive)
				// console.log('normal',normal)
				
				
				// model  模型
				
				function onProgress( xhr ) {
				
					if ( xhr.lengthComputable ) {
				
						const percentComplete = xhr.loaded / xhr.total * 100;
						console.log( 'model ' + Math.round( percentComplete, 2 ) + '% downloaded' );
				
					}
				
				}
				
				function onError() {}
				
				const loader = new GLTFLoader( manager );
				loader.load(_this.src, function ( obj ) {
				
					_this.object = obj.scene;
					console.log('模型',_this.object)
					//添加颜色
					obj.scene.traverse( function ( child ) {
						if ( child.isMesh ) {
							child.material.emissive =  child.material.color;
							child.material.emissiveMap = child.material.map ;
						}
					});
				}, onProgress, onError );

				//网格辅助线  GridHelper

				// const gridHelper = new THREE.GridHelper(1, 2, 0x888888, 0x444444);
				// this.scene.add(gridHelper);

				//环境光源  AmbientLight

				const ambientLight = new THREE.HemisphereLight( 0xffffff, 0x999999, 1 );
				this.scene.add(ambientLight);

				//点光源  PointLight
				

				//渲染器

				this.renderer = new THREE.WebGLRenderer({
					antialias: true
				});
				this.renderer.setPixelRatio(window.devicePixelRatio); //setPixelRatio  设置设备像素比。通常用于避免HiDPI设备上绘图模糊
				this.renderer.setSize(window.innerWidth, window
					.innerHeight
				); //setSize  输出canvas的大小调整为(width, height)并考虑设备像素比，且将视口从(0, 0)开始调整到适合大小 将updateStyle设置为false以阻止对canvas的样式做任何改变。
				// this.renderer.outputEncoding = THREE.sRGBEncoding;

				this.container.appendChild(this.renderer.domElement); //添加到节点末尾

				//轨道控制器

				this.controls = new OrbitControls(this.camera, this.renderer.domElement);
				this.controls.screenSpacePanning = true; //定义平移时如何平移相机的位置。如果为 true，则相机在屏幕空间中平移。否则，相机会在与相机向上方向正交的平面中平移。默认为假。
				this.controls.minDistance = 15; //最小缩放
				this.controls.maxDistance = 40; //最大距离
				// this.controls.target.set(0, 2, 0); //焦点

				//性能插件

				// this.stats = new Stats();
				// this.container.appendChild(this.stats.dom);

				//

				window.addEventListener('resize', this.onWindowResize);
				this.loading = false
			},
			onWindowResize() {

				this.camera.aspect = window.innerWidth / window.innerHeight;
				this.camera.updateProjectionMatrix();

				this.renderer.setSize(window.innerWidth, window.innerHeight);

			},

			animate() {

				requestAnimationFrame(this.animate);

				this.render();
				// this.stats.update();

			},
			render() {
				const delta = this.clock.getDelta();
				if (this.anms && this.object) {
					// this.object.rotation.z += 0.01;
					// this.object.rotation.x += 0.01;
					this.object.rotation.y += 0.01;
				}
				if (this.mixer !== undefined) {
					// this.mixer.update(delta);//更新

				}

				this.renderer.render(this.scene, this.camera);
			}

		}
	}
</script>
<style>
	.load{
		width: 100%;
		/* position: fixed; */
		top: 45vh;
		text-align: center;
		color: #b5b5b5;
		/* line-height: 450px; */
	}
	#container {
		position: absolute;
		top: 20rpx;
		width: 100%;
		height: 100%;
	}
</style>
